﻿using Leo.Blog.DAL.SysModule;
using Leo.Blog.Model;
using Leo.Blog.ViewModel;
using Leo.Blog.ViewModel.SysModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Leo.Blog.BLL.SysModule
{
    public class Sys_OrgInfo_B
    {
        /// <summary>
        /// 获取所有的组织信息，分页使用
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="parentId">根节点都为0，如果查询全部，则parentId=-1</param>
        /// <returns></returns>
        public static List<SysOrgInfoVM> GetOrgInfos(int pageIndex, int pageSize, out int totalCount, int parentId = -1)
        {
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            List<Sys_OrgInfo> listOrgs;
            if (parentId == -1)
            {
                listOrgs = _sysOrgInfoD.LoadPageEntities(pageIndex, pageSize, out totalCount,
                    null, true, m => m.OrgId).ToList();
            }
            else
            {
                //m => m.ParentOrgId == parentId
                // m => ("-" + m.OrgPath + "-").Contains("-" + parentId + "-")
                listOrgs = _sysOrgInfoD.LoadPageEntities(pageIndex, pageSize, out totalCount,
                    m => ("-" + m.OrgPath + "-").Contains("-" + parentId + "-"), true, m => m.OrgId).ToList();
            }

            var listSysOrgInfoVM = (from lsm in listOrgs
                                   select new SysOrgInfoVM
                                   {
                                       OrgId = lsm.OrgId,
                                       OrgName = lsm.OrgName,
                                       OrgDesc = lsm.OrgDesc,
                                       ParentOrgId = lsm.ParentOrgId,
                                       ParentName = lsm.ParentName,
                                       OrgPath = lsm.OrgPath,
                                       SortNo = lsm.SortNo,
                                       IsAutoExpend = lsm.IsAutoExpend,
                                       IconName = lsm.IconName,
                                       IsEnable = lsm.IsEnable,
                                       CreateBy = lsm.CreateBy,
                                       CreateDT = lsm.CreateDT
                                   }).ToList();
            return listSysOrgInfoVM;
        }
        /// <summary>
        /// 获取所有的组织信息
        /// </summary>
        /// <returns></returns>
        public static List<Sys_OrgInfo> GetSysOrgsAll()
        {
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            List<Sys_OrgInfo> Orgs = _sysOrgInfoD.LoadList().ToList();
            return Orgs;
        }
        /// <summary>
        /// 获取所有有效的组织信息
        /// </summary>
        /// <returns></returns>
        public static List<Sys_OrgInfo> GetSysOrgsAllIsEnable()
        {
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            List<Sys_OrgInfo> Orgs = _sysOrgInfoD.LoadList(m => m.IsEnable == 1).ToList();
            return Orgs;
        }
        /// <summary>
        /// 选择孩子List
        /// </summary>
        /// <param name="listOrgs"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private static List<Sys_OrgInfo> GetChildrenByParentId(List<Sys_OrgInfo> listOrgs, int parentId = 0)
        {
            List<Sys_OrgInfo> listChilren = listOrgs.Where(m => m.ParentOrgId == parentId).OrderBy(m => m.SortNo).ToList();
            return listChilren;
        }

        /// <summary>
        /// 递归生成模组树
        /// </summary>
        /// <param name="rootNode">树的根节点</param>
        /// <param name="listOrgs">生成数的所有节点</param>
        /// <param name="parentId">父节点id,默认根节点ID为0</param>
        public static void GetTree(TreeNode rootNode, List<Sys_OrgInfo> listOrgs, int parentId)
        {
            var listParent = GetChildrenByParentId(listOrgs, parentId);
            foreach (var item in listParent)
            {
                var listChild = GetChildrenByParentId(listOrgs, item.OrgId);
                TreeNode tn = new TreeNode();
                tn.Id = item.OrgId;
                tn.Text = item.OrgName;
                //tn.IconName = item.IconName;
                tn.State = item.IsAutoExpend.Value == 1 ? "open" : "closed";
                tn.IsChecked = false;
                tn.Attributes = new { ParentID = item.ParentOrgId };//默认设置
                if (listChild != null)
                {
                    GetTree(tn, listOrgs, item.OrgId);
                }
                rootNode.Children.Add(tn);
            }
        }
        //根据所有模块信息生成树
        public static void GetTreeByAllList(TreeNode rootNode, int parentId)
        {
            List<Sys_OrgInfo> OrgList = GetSysOrgsAll();
            GetTree(rootNode, OrgList, parentId);
        }
        //根据所有有效的模块生成树
        public static void GetTreeByAllIsEnable(TreeNode rootNode, int parentId)
        {
            List<Sys_OrgInfo> OrgList = GetSysOrgsAllIsEnable();
            GetTree(rootNode, OrgList, parentId);
        }

        public static SysOrgInfoVM FindSingle(int OrgId)
        {
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            Sys_OrgInfo Orgs = _sysOrgInfoD.FindSingle(m => m.OrgId == OrgId);
            if (Orgs != null)
            {
                SysOrgInfoVM vm = new SysOrgInfoVM
                {
                    OrgId = Orgs.OrgId,
                    OrgName = Orgs.OrgName,
                    OrgDesc = Orgs.OrgDesc,
                    ParentOrgId = Orgs.ParentOrgId,
                    ParentName = Orgs.ParentName,
                    SortNo = Orgs.SortNo,
                    OrgPath = Orgs.OrgPath,
                    IsAutoExpend = Orgs.IsAutoExpend,
                    IconName = Orgs.IconName,
                    IsEnable = Orgs.IsEnable,
                    CreateBy = Orgs.CreateBy,
                    CreateDT = Orgs.CreateDT
                };
                return vm;
            }
            return null;
        }

        public static SysOrgInfoVM AddorUpdate(SysOrgInfoVM model)
        {
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            Sys_OrgInfo Org = _sysOrgInfoD.FindSingle(m => m.OrgId == model.OrgId);
            if (Org == null)
            {
                #region 增加
                Sys_OrgInfo sysMOrg = new Sys_OrgInfo
                {
                    OrgName = model.OrgName,
                    OrgDesc = model.OrgDesc,
                    ParentOrgId = model.ParentOrgId,
                    ParentName = model.ParentName,
                    OrgPath = model.OrgPath,
                    SortNo = model.SortNo,
                    IsAutoExpend = model.IsAutoExpend,
                    IconName = model.IconName,
                    IsEnable = model.IsEnable,
                    CreateBy = model.CreateBy,
                    CreateDT = DateTime.Now,
                    LastEditBy = model.CreateBy,
                    LastEditDT = DateTime.Now
                };
                Sys_OrgInfo obj = _sysOrgInfoD.AddEntity(sysMOrg);
                if (obj != null)
                {
                    return model;
                }
                return null;
                #endregion
            }
            else
            {
                string srcOrgPath = Org.OrgPath;
                
                #region 修改
                Org.OrgName = model.OrgName;
                Org.OrgDesc = model.OrgDesc;
                Org.ParentOrgId = model.ParentOrgId;
                Org.ParentName = model.ParentName;
                Org.OrgPath = model.OrgPath;
                Org.SortNo = model.SortNo;
                Org.IsAutoExpend = model.IsAutoExpend;
                Org.IconName = model.IconName;
                Org.IsEnable = model.IsEnable;
                Org.LastEditBy = model.CreateBy;
                Org.LastEditDT = DateTime.Now;

                if (_sysOrgInfoD.UpdateEntity(Org))
                {
                    if (!srcOrgPath.Equals(model.OrgPath))
                    {
                        string orgId = "-" + Org.OrgId + "-";
                        //修改后路径相同，不更新子项路径，路径不相同，需要更新路径
                        string sql = @"update Sys_OrgInfo set OrgPath=(select OrgPath+'-'+cast(OrgId as varchar) FROM Sys_OrgInfo WHERE OrgId='" + Org.OrgId
                            + "')  where OrgId in(select OrgId from Sys_OrgInfo where ('-'+OrgPath+'-') like '%-" + Org.OrgId + "-%')";
                        int res = _sysOrgInfoD.ExecuteCommand(sql);
                    }
                    return model;
                }
                return null;
                #endregion
            }
        }

        public static bool UpdateIsEnable(int OrgId, int userId)
        {
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            Sys_OrgInfo Org = _sysOrgInfoD.FindSingle(m => m.OrgId == OrgId);
            if (Org != null)
            {
                Org.IsEnable = Org.IsEnable == 1 ? 0 : 1;
                Org.LastEditBy = userId;
                Org.LastEditDT = DateTime.Now;
                return _sysOrgInfoD.UpdateEntity(Org);
            }
            return false;
        }

        public static bool Delete(int OrgId)
        {
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            Sys_OrgInfo Org = _sysOrgInfoD.FindSingle(m => m.OrgId == OrgId);
            if (Org != null)
            {
                return _sysOrgInfoD.DeleteEntity(Org);
            }
            return false;
        }

        public static bool DeleteList(string ids)
        {
            List<Sys_OrgInfo> OrgList = new List<Sys_OrgInfo>();
            foreach (string id in ids.Split(','))
            {
                if (string.IsNullOrEmpty(id)) { continue; }
                OrgList.Add(new Sys_OrgInfo { OrgId = int.Parse(id) });
            }
            Sys_OrgInfo_D _sysOrgInfoD = new Sys_OrgInfo_D();
            return _sysOrgInfoD.DeleteList(OrgList);
        }
    }
}
